<template>
  <div class="app-container">
    <div style="text-align: center;margin-bottom: 30px">
      {{ createStatus ? '新增' : '更新' }}
    </div>
    <el-form :model="enterpriseForm" ref="enterpriseForm" :rules="enterpriseFormRules" label-width="150px">
      <el-row :gutter="10">
        <el-col :span="6">
          <el-form-item label="主体logo" prop="logo">
            <el-upload
                class="avatar-uploader"
                :action="uploadImg"
                :headers="headers"
                :data="{type:'logo'}"
                :show-file-list="false"
                :on-success="handleAvatarSuccess"
                :on-progress="uploadImgProcess"
                :before-upload="beforeAvatarUpload">
              <img v-if="enterpriseForm.logo&& imgFlag == false" :src="enterpriseForm.logo" class="avatar">
              <el-progress v-if="imgFlag == true" type="circle" :percentage="imgUploadPercent"
                           style="margin-top:30px;"></el-progress>
              <i v-else-if="!enterpriseForm.logo&& imgFlag == false" class="el-icon-plus avatar-uploader-icon"></i>
            </el-upload>
          </el-form-item>
        </el-col>
        <el-col :span="18">
          <el-col :span="12">
            <el-form-item label="所属行政区划" prop="enterpriseLocal">
              <city-select :local="enterpriseForm.enterpriseLocal" v-on:handleChange="getCity"></city-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="单位名称" prop="name">
              <el-input type="text" v-model="enterpriseForm.name" placeholder="请输入主体名称" clearable></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item v-if="dominantType==6||dominantType==-1" label="直属消防管理单位" prop="detachmentId">
              <el-cascader
                  v-model="orgIdList"
                  :options="orgTree"
                  :props="{ checkStrictly: true,expandTrigger: 'hover',value:'ucId',label:'name' }"
                  placeholder="请选择直属消防管理单位"
                  style="width: 100%"
                  @change="orgChange"
              >
              </el-cascader>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item v-if="dominantType==6" label="警务室" prop="policeId">
              <el-select v-model="enterpriseForm.policeId" filterable placeholder="请选择警务室" style="width: 100%">
                <el-option v-for="(item,index) in policeStationList" :key="index" :value="item.ucId"
                           :label="item.name"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item v-if="dominantType==6" label="维保企业" prop="maintenanceId">
              <el-select v-model="enterpriseForm.maintenanceId" filterable placeholder="请选择维保企业" style="width: 100%">
                <el-option v-for="(item,index) in maintenanceList" :key="index" :value="item.ucId"
                           :label="item.name"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item v-if="dominantType==6" label="主体建筑类型" prop="monomer">
              <el-radio-group v-model="enterpriseForm.monomer">
                <el-radio v-for="dict in monomerOptions" :label="dict.dictValue" :key="dict.dictValue">
                  {{ dict.dictLabel }}
                </el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="联系人" prop="contacts">
              <el-input type="text" v-model="enterpriseForm.contacts" placeholder="请输入主体联系人" clearable></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="联系人电话" prop="mobile">
              <el-input type="text" v-model="enterpriseForm.mobile" placeholder="请输入联系人电话" clearable></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="固话" prop="tel">
              <el-input type="text" v-model="enterpriseForm.tel" placeholder="请输入主体固话" clearable></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="管理员账号" prop="userName" v-if="createStatus">
              <el-input type="text" v-model="enterpriseForm.userName" placeholder="请输入超管账号" clearable></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="管理员密码" prop="password" v-if="createStatus">
              <el-input type="password" v-model="enterpriseForm.password" placeholder="请输入超管密码" clearable></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item v-if="dominantType==6" label="主体规模" prop="size">
              <el-input type="number" v-model="enterpriseForm.size" placeholder="请输入主体规模（多少人）" clearable></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="详细地址" prop="address">
              <el-input type="text" v-model="enterpriseForm.address" placeholder="请输入详细地址" clearable></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="管理员" prop="adminId" v-if="!createStatus">
              <el-select v-model="enterpriseForm.adminId" placeholder="请选择责任人" style="width: 100%">
                <el-option v-for="(item,index) in userList" :key="index" :value="item.ucId"
                           :label="item.name"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="联动消防力量" v-if="dominantType==6" prop="unionEnterprise">
              <el-select v-model="unionEnterpriseList" filterable @change="unionChange" multiple placeholder="请选择关联主体"
                         style="width: 100%"
                         clearable>
                <el-option v-for="item in enterpriseList"
                           :key="item.id" :value="item.id"
                           :label="item.name">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="是否工业模式" v-if="dominantType==6" prop="industrial">
              <el-radio-group v-model="enterpriseForm.industrial">
                <el-radio v-for="dict in yesOrNoOptions" :label="dict.dictValue" :key="dict.dictValue">
                  {{ dict.dictLabel }}
                </el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <baidu-map
                　class="bm-view"
                　:center="{ lng: enterpriseForm.longitude, lat: enterpriseForm.latitude }"
                　:zoom="17"
                　:scroll-wheel-zoom="true"
                @ready="handler"
                center="哈密市"
                　@click="getClickInfo"
                　@moving="syncCenterAndZoom"
                　@moveend="syncCenterAndZoom"
                　@zoomend="syncCenterAndZoom"
            >
              <bm-view style="width: 90%; height: 500px; margin-left: 5%;margin-bottom: 10px"></bm-view>
              <bm-marker
                  :position="{ lng: enterpriseForm.longitude, lat: enterpriseForm.latitude }"
                  :dragging="true"
                  animation="BMAP_ANIMATION_BOUNCE"
              >

                <bm-info-window :show="show">当前坐标</bm-info-window>
              </bm-marker>
              <bm-control style="margin-top: 10px; margin-left: 10px">
                <bm-auto-complete v-model="enterpriseForm.address" :sugStyle="{ zIndex: 999999 }">
                  <input
                      type="text"
                      placeholder="请输入搜索关键字"
                      class="serachinput"
                  />
                </bm-auto-complete>
              </bm-control>
              <bm-local-search
                  :keyword="enterpriseForm.address"
                  :auto-viewport="true"
                  style="width: 0px; height: 0px; overflow: hidden"
              >
              </bm-local-search>
              <bm-navigation anchor="BMAP_ANCHOR_TOP_RIGHT"></bm-navigation>
            </baidu-map>
          </el-col>
        </el-col>
      </el-row>
      <el-dialog title="地图位置" :visible.sync="mapVisible" width="50%">
        <baidu-map class="map-view" map-type="BMAP_NORMAL_MAP" center="哈密市" :zoom="15" :scroll-wheel-zoom="true">
          <bm-marker :position="{lng: enterpriseForm.longitude, lat: enterpriseForm.latitude}" :dragging="false"
                     animation="BMAP_ANIMATION_BOUNCE">
          </bm-marker>
        </baidu-map>
      </el-dialog>
    </el-form>

    <div slot="footer" style="text-align: center" class="dialog-footer">
      <el-button @click="cancelEnterprise">取 消</el-button>
      <el-button :loading="addLoading" v-if="createStatus" type="primary" @click="createEnterprise">创 建</el-button>
      <el-button :loading="addLoading" v-else type="primary" @click="updateInEnterpriseDominant">修 改</el-button>
    </div>
  </div>
</template>

<script>
import {addInEnterpriseDominant, getInEnterpriseDominantVo, updateInEnterpriseDominant} from "@/api/enterprise";
import CitySelect from "@/components/citySelect/index.vue";
import {uploadImg, getOption} from "@/api/common";
import {getToken} from "@/utils/auth";
import {getInEnterpriseDominantList} from "@/api/enterpriseDominant";
import {getInUserList} from "@/api/enterprise";
import {handleTree} from "@/utils";
import {isExit} from "@/api/validator";
import BMap from "vue-baidu-map";

export default {
  name: "adminEdit",
  components: {CitySelect,},
  data() {
    return {
      uploadImg,
      enterpriseForm: {
        latitude: "",
        longitude: "",
        industrial: "10",

      },
      enterpriseFormRules: {
        dominantType: [{required: true, message: '主体类型不能为空', trigger: 'blur'}],
        detachmentId: [{required: true, message: '所属支队不能为空', trigger: 'change'}],
        contacts: [{required: true, message: '联系人不能为空', trigger: 'change'}],
        enterpriseLocal: [{required: true, message: '所属行政区划不能为空', trigger: 'blur'}],
        brigadeId: [{required: true, message: '所属大队不能为空', trigger: 'change'}],
        squadronId: [{required: true, message: '所属中队不能为空', trigger: 'change'}],
        policeId: [{required: true, message: '所属警务站不能为空', trigger: 'change'}],
        maintenanceId: [{required: true, message: '所属维保公司不能为空', trigger: 'change'}],
        buildId: [{required: true, message: '所属建筑不能为空', trigger: 'change'}],
        mobile: [{required: true, message: '联系人电话不能为空', trigger: 'blur'}],
        address: [{required: true, message: '详细地址不能为空', trigger: 'blur'}],
        name: [{required: true, message: '  主体名称不能为空', trigger: 'blur'}],
        userName: [
          {required: true, message: '超管账号不能为空', trigger: 'blur'},
          {
            validator: (rule, value, callback) => {
              if (!value) {
                callback(new Error('超管账号不能为空'))
              } else {
                isExit({userName: value, id: 0}).then(res => {
                  if (res.data) {
                    callback(new Error('超管账号已经存在'))
                  } else {
                    callback()
                  }
                })
              }
            },
            trigger: ['change', 'blur'],
          }
        ],
        password: [{required: true, message: '  超管密码不能为空', trigger: 'blur'}],
      },
      addLoading: false,
      imgFlag: false,
      imgUploadPercent: 0,
      cronPopover: false,
      cron: '',
      hidden: false,
      hidden1: false,
      maintenanceList: [],
      fireControlDetachmentList: [],
      fireControlBrigadeList: [],
      fireControlSquadronList: [],
      policeStationList: [],
      disasterEliminationEnterpriseList: [],
      fireControlCommandRoomList: [],
      userList: [],
      //消防机构列表
      orgList: [],
      //消防机构树
      orgTree: [],
      //选中消防机构数组
      orgIdList: [],
      //安全主体列表
      enterpriseList: [],
      //关联安全主体id
      unionEnterpriseList: [],
      orgTypeOptions: [],
      monomerOptions: [],
      yesOrNoOptions: [],
      mapVisible: false,
      address: "",
      mapStyle: {
        width: "100%",
        height: this.mapHeight + "px",
      },
      center: {lng: "", lat: ""},
      zoom: 15,
      keyword: "",
      show: false,
      BMap: null
    }
  },
  computed: {
    createStatus() {
      return this.$route.params.ucId == '0'
    },
    dominantType() {
      return parseInt(this.$route.query.type)
    },
    headers() {
      return {
        'authorization': getToken()
      }
    },
  },
  created() {
    if (this.dominantType == 6) {
      this.getEnterpriseList({})
    } else if (this.dominantType == -1) {
      this.getOrgList({customize: "and dominant_type < 4 "})
    }
    if (!this.createStatus) {
      let ucId = this.$route.params.ucId
      this.getInEnterpriseDominantVo(ucId)
      this.getInUserList(ucId)
    }
    this.getDicts("org_type").then(res => {
      if (res.data.data) {
        res.data.data.forEach(r => {
          this.orgTypeOptions.push({dictValue: parseInt(r.dictValue), dictLabel: r.dictLabel})
        })
      }
    });
    this.getDicts("monomer_type").then(response => {
      this.monomerOptions = response.data.data;
    });
    this.getDicts("yes_or_no").then(response => {
      this.yesOrNoOptions = response.data.data;
    });
  },
  methods: {
    //地图点击事件。
    getClickInfo(e) {
      this.enterpriseForm.longitude = e.point.lng;
      this.enterpriseForm.latitude = e.point.lat;
      const geocoder = new BMap.Geocoder() // 创建地址解析器的实例
      geocoder.getLocation(e.point, rs => {
        console.log(rs.addressComponents) // 结构化的地址描述(object)
        const province = rs.addressComponents.province // 省
        const city = rs.addressComponents.city // 城市
        const district = rs.addressComponents.district // 区县
        const street = rs.addressComponents.street // 街道
        const streetNumber = rs.addressComponents.streetNumber// 门牌号
        this.enterpriseForm.address = province + city + district + street + streetNumber // 组装成地址
      })
    },
    syncCenterAndZoom(e) {
      setTimeout(() => {
        this.show = false;
      }, 10000);
      if (this.center.lng) {
        this.loading = false;
      } else {
        this.loading = true;
      }
      this.zoom = e.target.getZoom();
    },
    //自动定位
    handler({BMap, map}) {
      this.BMap = BMap
      const that = this;
      // 获取自动定位方法
      var geolocation = new BMap.Geolocation();
      // 获取自动定位获取的坐标信息
      geolocation.getCurrentPosition(
          function (r) {
            that.center.lng = r.longitude;
            that.center.lat = r.latitude;
          },
          {enableHighAccuracy: true}
      );
    },
    createEnterprise() {
      this.addLoading = true
      this.setDominantType()
      this.$refs['enterpriseForm'].validate(valid => {
        if (valid) {
          this.enterpriseForm.monomer = parseInt(this.enterpriseForm.monomer)
          addInEnterpriseDominant(this.enterpriseForm).then(res => {
            this.addLoading = false
            this.$notify.success({
              title: '成功',
              message: "添加主体成功"
            })
            this.cancelEnterprise()
          }).catch(res => {
            this.addLoading = false
            this.$notify.error({
              title: '失败',
              message: res.msg
            })
          })
        } else {
          this.addLoading = false
          console.log("表单验证不通过")
        }
      })
    },
    orgChange(val) {
      const orgType = ["detachmentId","brigadeId","squadronId"]
      for(let i=0;i<val.length;i++){
        this.enterpriseForm[orgType[i]] = val[i]
      }
    },
    //获取主体数据列表
    unionChange() {
      this.enterpriseForm.unionEnterprise = this.unionEnterpriseList.join(",")
    },
    getEnterpriseList(param) {
      getInEnterpriseDominantList(param).then(res => {
        res.data.forEach(d => {
          //封装各类数据
          const org = {id: d.id, ucId: d.ucId, parentId: d.parentId, name: d.name}
          switch (d.dominantType) {
            case 0:
            case 1:
            case 2:
            case 3:
            case 4:
              this.orgList.push(org)
              break
            case 5:
              this.policeStationList.push(org)
              break
            case 6:
              this.enterpriseList.push(org)
              break
            case 7:
              this.maintenanceList.push(org)
              break
          }
        })
        //行政区划树
        this.orgTree = handleTree(this.orgList, 'ucId', 'parentId', "")
      }).catch(error => {
        console.log(error)
      })
    },
    getOrgList(param) {
      getInEnterpriseDominantList(param).then(res => {
        //行政区划树
        this.orgTree = handleTree(res.data, 'ucId', 'parentId', "")
      }).catch(error => {
        console.log(error)
      })
    },
    changeCron(val) {
      this.cron = val
    },
    getInEnterpriseDominantVo(val) {
      getInEnterpriseDominantVo({ucId: val}).then(res => {
        // console.log(res)
        this.enterpriseForm = res.data
        if (this.enterpriseForm.monomer) {
          this.enterpriseForm.monomer = "1";
        } else {
          this.enterpriseForm.monomer = "0";
        }
        this.enterpriseForm.enterpriseLocal = [this.enterpriseForm.province, this.enterpriseForm.city, this.enterpriseForm.county]
        if (res.data.unionEnterprise) {
          this.unionEnterpriseList = []
          let unionArray = res.data.unionEnterprise.split(",")
          unionArray.forEach(u => {
            this.unionEnterpriseList.push(u - 0)
          })
        }
        this.orgIdList = []
        if (res.data.detachmentId) {
          this.orgIdList.push(res.data.detachmentId)
        }
        if (res.data.brigadeId) {
          this.orgIdList.push(res.data.brigadeId)
        }
        if (res.data.squadronId) {
          this.orgIdList.push(res.data.squadronId)
        }
        if (res.data.dominantType < 5) {
          this.enterpriseForm.dominantType = -1
        }
      }).catch(res => {
        console.log("失败")
      })
    },
    cancelEnterprise() {
      window.history.back()
    },
    setDominantType() {
      // 消防管理单位
      if (this.dominantType === -1) {
        if (this.enterpriseForm.brigadeId) {
          this.enterpriseForm.parentId = this.enterpriseForm.brigadeId
          this.enterpriseForm.dominantType = 4
        } else if (this.enterpriseForm.detachmentId) {
          this.enterpriseForm.parentId = this.enterpriseForm.detachmentId
          this.enterpriseForm.dominantType = 3
        }
      }else{
        this.enterpriseForm.dominantType = this.dominantType
      }
    },
    updateInEnterpriseDominant() {
      this.addLoading = true
      this.setDominantType()
      this.$refs['enterpriseForm'].validate(valid => {
        if (valid) {
          this.enterpriseForm.monomer = parseInt(this.enterpriseForm.monomer)
          updateInEnterpriseDominant(this.enterpriseForm).then(res => {
            this.addLoading = false
            this.$notify.success({
              title: '成功',
              message: "更新主体成功"
            })
            this.cancelEnterprise()
          }).catch(res => {
            this.addLoading = false
            this.$notify.error({
              title: '失败',
              message: res.msg
            })
          })
        } else {
          this.addLoading = false
          console.log("表单验证不通过")
        }
      })
    },
    handleAvatarSuccess(res, file) {
      //图片上传成功
      console.log(res)
      this.imgFlag = false
      this.enterpriseForm.logo = res.data;
    },
    uploadImgProcess(event, file, fileList) {
      this.imgFlag = true;
      this.imgUploadPercent = file.percentage.toFixed(0);
    },
    beforeAvatarUpload(file) {
      const isJPG = file.type === 'image/jpeg' || file.type === 'image/png';
      const isLt2M = file.size / 1024 / 1024 < 2;
      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG、png格式!');
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!');
      }
      return isJPG && isLt2M;
    },
    //选择位置信息
    getCity(val) {
      this.enterpriseForm.enterpriseLocal = val
      this.enterpriseForm.province = val[0]
      this.enterpriseForm.city = val[1]
      this.enterpriseForm.county = val[2]
    },
    getInEnterpriseDominantList(val, obj) {
      getInEnterpriseDominantList({dominantType: val}).then(res => {
        this[obj] = res.data
      }).catch(error => {
        console.log(error)
      })
    },
    getInUserList(val) {
      getInUserList({deleted: false, flagId: val}).then(res => {
        this.userList = res.data
      }).catch(error => {
        alert("获取用户列表失败")
      })
    },
  }

}
</script>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.avatar-uploader .el-upload:hover {
  border-color: #409EFF;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 149px;
  height: 149px;
  line-height: 149px;
  text-align: center;
}

.avatar {
  width: 149px;
  height: 149px;
  display: block;
}
</style>
